package com.tc.excel.handler;

import com.tc.excel.JxlExcelUtils;
import com.tc.excel.anno.RequestExcel;
import com.tc.excel.anno.ResponseExcel;
import org.springframework.core.MethodParameter;
import org.springframework.core.ResolvableType;
import org.springframework.util.Assert;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.List;

/**
 * @Auther: tianchao
 * @Date: 2025/2/14 22:04
 * @Description:
 */
public class ExcelArgumentResolvers implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(RequestExcel.class) && List.class == parameter.getParameterType();
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Class<?> parameterType = parameter.getParameterType();
        Assert.isAssignable(parameterType, List.class,"入参必须是List或者List的父类" );
        RequestExcel requestExcel =  parameter.getParameterAnnotation(RequestExcel.class);
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        Assert.notNull(request,"Excel导入httpServletRequest不能为空");
        InputStream inputStream = null;
        if (request instanceof MultipartRequest){
            MultipartFile file = ((MultipartRequest) request).getFile(requestExcel.fileName());
            Assert.notNull(file,"Excel导入文件不能为空");
            inputStream = file.getInputStream();
        }else{
            // 抛出异常或返回错误信息
            throw new IllegalArgumentException("请求必须是multipart/form-data类型，请确保正确上传文件");
        }
        Class<?> excelModalClass = ResolvableType.forMethodParameter(parameter).getGeneric(0).resolve();
        Assert.notNull(excelModalClass,"Excel导入文件目标类型不能为空");
        int headNumber = requestExcel.headNumber();
        return JxlExcelUtils.importExcel(inputStream,excelModalClass,headNumber);
    }
}
